package ch13
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.utils.setTimeout;

	import utils.Segment;

	public class Walking4 extends Sprite
	{
		private var segment0:Segment;
		private var segment1:Segment;
		private var segment2:Segment;
		private var segment3:Segment;
		private var cycle:Number = 0;
		private var offset:Number = -Math.PI / 2;

		public function Walking4()
		{
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			setTimeout(init, 500);
		}

		private function init():void
		{

			segment0 = new Segment(100, 30);
			addChild(segment0);
			segment0.x = 200;
			segment0.y = 100;

			segment1 = new Segment(100, 20);
			addChild(segment1);
			segment1.x = segment0.getPin().x;
			segment1.y = segment0.getPin().y;

			segment2 = new Segment(100, 30);
			addChild(segment2);
			segment2.x = 200;
			segment2.y = 100;

			segment3 = new Segment(100, 20);
			addChild(segment3);
			segment3.x = segment2.getPin().x;
			segment3.y = segment2.getPin().y;

			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}

		private function onEnterFrame(event:Event):void
		{
			walk(segment0, segment1, cycle);
			walk(segment2, segment3, cycle + Math.PI);
			cycle += .05;
		}

		private function walk(segA:Segment, segB:Segment, cyc:Number):void
		{
			/**
			 * 看起来还是不像真正在走路。也许它是在漫不经心地踢球，或是在练习芭蕾舞，但就是不像在走路。
			 * 这是因为两个关节在同一时刻内向同一方向运动。它们是完全同步的，而真正的行走过程，并不是这样的。
			 * 关节的同步是因为它们都使用了相同的循环变量来计算各自的角度。要让它们不再同步，
			 * 我们应采用 cycle0 和 cycle1 变量，但是可以不做这么大的改变。只需要加入循环的偏移量求出 angle1 即可.
			 * */
//			var angle0:Number = Math.sin(cycle) * 45 + 90;
//			var angle1:Number = Math.sin(cycle) * 45 + 45;
			var angleA:Number = Math.sin(cyc) * 45 + 90;
			var angleB:Number = Math.sin(cyc + offset) * 45 + 45;
			segA.rotation = angleA;
			segB.rotation = segA.rotation + angleB;
			segB.x = segA.getPin().x;
			segB.y = segA.getPin().y;
		}

	}
}
